﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DotConsulting.VisualStudio.BuildOutputCopy.Model
{
    public class SolutionBuildInfo
    {

        private EnvDTE.Solution _DteSolution;
        public string ActiveConfiguration { get; private set; }
        public string ActivePlatform { get; private set; }
        public ObservableCollection<ProjectBuildInfo> ProjectsBuildInfo { get; private set; }

        public SolutionBuildInfo(EnvDTE.Solution dteSolution)
        {
            _DteSolution = dteSolution;
            Refresh();
        }

        public void Refresh()
        {
            var activeSolutionConfiguration = (EnvDTE80.SolutionConfiguration2)_DteSolution.SolutionBuild.ActiveConfiguration;
            if (activeSolutionConfiguration != null)
            {
                ActiveConfiguration = activeSolutionConfiguration.Name;
                ActivePlatform = activeSolutionConfiguration.PlatformName;
                var result = new List<ProjectBuildInfo>();
                foreach (EnvDTE.Project p in _DteSolution.Projects)
                {
                    BuildInternal(p, ref result);
                }

                ProjectsBuildInfo = new ObservableCollection<ProjectBuildInfo>(result);
            }
        }

        private void BuildInternal(EnvDTE.Project project, ref List<ProjectBuildInfo> result)
        {

            if (project == null)
            {
                return;
            }

            if (project.Kind == "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}") // Solution folder
            {
                foreach (EnvDTE.ProjectItem pi in project.ProjectItems)
                {
                    BuildInternal(pi.SubProject, ref result);
                }
            }
            else if (project.Kind == "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /* c# */ || project.Kind == "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}" /* VB.NET */)
            {
                result.Add(new ProjectBuildInfo(project, this));
            }
            else
            {
                foreach (EnvDTE.ProjectItem pi in project.ProjectItems)
                {
                    BuildInternal(pi.SubProject, ref result);
                }
            }
        }
    }
}
